/**
 * @file        interface.cpp
 * @brief       gtdshell command line interface handling.
 *
 * @author      Emre Turkay <emreturkay at gmail>
 * @date        May.31.2008
 */

#include "interface.hpp"
#include "quote_separator.hpp"

#include <boost/tokenizer.hpp>

#include <algorithm>

action_info::action_info(function_type f, const std::string& desc)
    : function_(f),
      description_(desc)
{
}

void action_info::operator()(const args_type& args)
{
    function_(args);
}

void interface::command(const std::string& text, function_type action,
                        const std::string& description)
{
    actions_[text] = action_info(action, description);
}

bool interface::process()
{
    std::string line;
    std::cout << "> ";
    std::getline(std::cin, line);

    if (std::cin.eof())
    {
        std::cout << "bye" << std::endl;
        return false;
    }

    std::vector<std::string> result;

    typedef boost::tokenizer<quote_separator> tok_type;
    tok_type tok(line);
    std::copy(tok.begin(), tok.end(), std::back_inserter(result));

    if (line.size())
    {
        actions_type::iterator map_iter = actions_.find(result[0]);
        if (map_iter == actions_.end())
            std::cout << "Unknown command: " << result[0] << std::endl;
        else
        {
            result.erase(result.begin());
            map_iter->second(result);
        }
    }

    return true;
}

void interface::help()
{
    for(actions_type::const_iterator i = actions_.begin();
            i != actions_.end(); ++i)
    {
        std::cout << i->first << '\t' << i->second.description() << std::endl;
    }
}

std::ostream& interface::out()
{
    return std::cout;
}

std::istream& interface::in()
{
    return std::cin;
}

